package com.dundun.pattern.memento;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Gamer {
    private int money;
    private List<String> fruits;
    private Random random;
    private static String[] fruitname = {"苹果", "葡萄", "香蕉", "橘子"};

    public Gamer(int money) {
        this.money = money;
        fruits = new ArrayList<>();
        random = new Random();
    }

    public int getMoney() {
        return money;
    }

    public void bet() {
        int dice = random.nextInt(6) + 1;
        switch (dice) {
            case 1:
                money += 100;
                System.out.println("金币增加了");
                break;
            case 2:
                money /= 2;
                System.out.println("金币减少了");
                break;
            case 6:
                String f = getFruit();
                System.out.println("获得了水果：" + f);
                fruits.add(f);
                break;
            default:
                System.out.println("什么都没发生");
        }
    }

    public Memento createMemento() {
        Memento m = new Memento(money);
        for(String f : fruits) {
            if(f.startsWith("好吃的"))
                m.addFruit(f);
        }
        return m;
    }

    public void restoreMemento(Memento memento) {
        this.money = memento.getMoney();
        this.fruits = memento.getFruits();
    }

    private String getFruit() {
        String prefix = random.nextBoolean()?"好吃的":"";
        return prefix + fruitname[random.nextInt(fruitname.length)];
    }

    @Override
    public String toString() {
        return String.format("[money=%d, fruits=%s]", money, fruits);
    }
}
